<template>
  <el-scrollbar>
    <VueJsonPretty
      v-model:data="flowDef"
      :deep="3"
      editable
      showLength
      showLineNumber
      virtual
      style="border: 1px solid #606266"
    />
    <div
      style="
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin: 10px 0px;
      "
    >
      <el-button type="primary" @click="export2Text"> 导出文本 </el-button>
      <el-button type="primary" @click="importFromText">文本导入</el-button>
      <span>
        <CommonSelect
          v-model:defaultValue="data.defFlowId"
          :auto-query="true"
          label="flowName"
          value="id"
          url="/esflow/def/get/list"
          @change="handleTemplateChange"
        />
      </span>
      <el-button type="primary" @click="importFromTemplate">模板导入</el-button>
    </div>
    <el-input v-model="data.flowDefJson" type="textarea" :rows="8" />
  </el-scrollbar>
</template>

<script setup lang="ts" name="JsonView">
import { reactive } from "vue";
import CommonSelect from "@/components/commonSelect.vue";
import { useMessage, useMessageBox } from "@/hooks/message";
import VueJsonPretty from "vue-json-pretty";
import "vue-json-pretty/lib/styles.css";

const $emit = defineEmits(["loadFlow", "showAttrConfig"]);

const flowDef = defineModel<any[]>();

const data = reactive({
  defFlowId: "",
  flowDefJson: "",
  defFlow: {
    id: "",
    flowName: "未命名流程",
    flowKey: "",
    icon: {
      name: "file-icons:omnigraffle",
      bgc: "#4C87F3",
      color: "#FFFFFF"
    },
    formId: "",
    formName: "",
    status: "-1",
    version: 1,
    groupId: "1",
    remark: null,
    flowDef: ""
  }
});

const export2Text = () => {
  data.flowDefJson = JSON.stringify(flowDef.value);
};

const importFromText = () => {
  if (!data.flowDefJson) {
    useMessage().warning("请先导入数据");
    return;
  }
  flowDef.value = JSON.parse(data.flowDefJson);
};

const handleTemplateChange = (val, template) => {
  data.defFlow = template;
};

const importFromTemplate = async () => {
  if (!data.defFlowId) {
    useMessage().error("请先选择已有流程");
    return;
  }
  if (!data.defFlow) {
    useMessage().error("流程模板不存在");
    return;
  }
  useMessageBox()
    .confirm(`是否以${data.defFlow.flowKey}为模板导入流程配置`)
    .then(() => {
      flowDef.value = JSON.parse(data.defFlow.flowDef);
      data.defFlow.status = "0";
      data.defFlow.version = 1;
    });
};
</script>

<style lang="scss" scoped>
@use "@/assets/style/design/flow-drawer.scss";
</style>
